package com.appbee.core.client.event;

import com.google.web.bindery.event.shared.Event;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.google.web.bindery.requestfactory.shared.WriteOperation;

public class EntityChange<P> extends Event<EntityChange.Handler<P>>
{

	public interface Handler<P>
	{
		void onChange(EntityChange<P> event);
	}

	private static final Type<EntityChange.Handler<?>> TYPE = new Type<EntityChange.Handler<?>>();

	public static <P> HandlerRegistration registerForProxyType(	EventBus eventBus,
																Class<P> proxyType,
																EntityChange.Handler<P> handler)
	{
		return eventBus.addHandlerToSource(TYPE, proxyType, handler);
	}

	private final P entity;

	private final WriteOperation writeOperation;

	public EntityChange(P entity, WriteOperation writeOperation)
	{
		this.entity = entity;
		this.writeOperation = writeOperation;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Event.Type<Handler<P>> getAssociatedType()
	{

		return (Type) TYPE;
	}

	public P getEntity()
	{
		return entity;
	}

	/**
	 * Returns the {@link WriteOperation} associated with this instance.
	 * 
	 * @return a {@link WriteOperation} instance
	 */
	public WriteOperation getWriteOperation()
	{
		return writeOperation;
}

	@Override
	protected void dispatch(Handler<P> handler)
	{
		handler.onChange(this);
	}
}